单例模式(Singleton Pattern)

Ensure a class has only one instance, and provide a global point of access to it.

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例

iOS应用举例

NSNotificationCenter
UIApplication
NSUserDefaults

Rules

  1. 单例必须在程序生命周期中是唯一的

  2. 遵循第一条规则,也就是说确保单例的唯一性,大部分情况我们考虑的是单例必须是thread-safe(12306抢票时,如果每个人代表一个线程,要确保没有两个人买到同样的火车票,即在多线程并发的情况下能够保持逻辑正确,称作线程安全)

代码实现

Objective-C

+ (instancetype)sharedInstance{
    //我喜欢用GCD的方式
    static SingleTonClass *sharedInstance = nil; //unique-ness
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ //thread-safe
        sharedInstance = [[SingleTonClass alloc] init];
    });
    return sharedInstance;
}

PS:Objective-C中没有私有方法,你还是可以外部调用[[SingleTonClass alloc] init];,只能靠协议来保证

Swift

class SingleTonClass {
    //真是简洁如swift啊, 缺点调试工具不好用,变化太快
    static let sharedInstance = SingleTonClass() //thread-safe
    private init() {} //unique-ness
}

PS: swift中全局变量static变量是由dispatch_once保证原子性的(A.K.A thread-safe)

Python(Singleton, metaclass, _metaclass_)

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Logger(object):
    __metaclass__ = Singleton

Node.js(node单线程, Modules, Singleton)

var singleton = function singleton(){}

singleton.instance = null;

singleton.getInstance = function(){
    if(this.instance === null){
        this.instance = new singleton();
    }
    return this.instance;
}

module.exports = singleton.getInstance();

天才小飞猫
320 声望16 粉丝

引用和评论

0 条评论